using System.Threading;
using System.Threading.Tasks;
using MediatR;
using B.S.BasicData.EroorCode;
using B.S.BasicData.Domain;
using B.S.BasicData.Infrature;
using System.Linq;

public class RegisterHandler : IRequestHandler<RegisterRequest, ApiResult<string>>
{
    private readonly IBaseRepository<User> _userRepository;
    public RegisterHandler(IBaseRepository<User> userRepository)
    {
        _userRepository = userRepository;
    }

    public async Task<ApiResult<string>> Handle(RegisterRequest request, CancellationToken cancellationToken)
    {
        var users = await _userRepository.GetAllAsync();
        if (users.Any(u => u.UserName == request.UserName))
        {
            return ApiResult<string>.Fail("用户名已存在");
        }
        var user = new User
        {
            UserName = request.UserName,
            Password = request.Password
        };
        await _userRepository.AddAsync(user);
        return ApiResult<string>.Success(user.UserName, "注册成功");
    }
} 